package cn.zjitc.exam.controller;

import cn.zjitc.exam.domain.Product;
import cn.zjitc.exam.service.ProductService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProductService productService;

    // 分页查询
    @GetMapping("/list")
    public String list(@RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "1") int page,
                       @RequestParam(defaultValue = "10") int size,
                       Model model) {
        PageInfo<Product> pageInfo = productService.list(keyword,page, size);
        model.addAttribute("products", pageInfo.getList());
        model.addAttribute("page", pageInfo.getPageNum());
        model.addAttribute("size", pageInfo.getPageSize());
        model.addAttribute("total", pageInfo.getTotal());
        return "product/list";
    }

    // 跳转新增页面
    @GetMapping("/add")
    public String addPage() {
        return "product/add";
    }

    // 新增
    @PostMapping("/add")
    public String add(Product product) {
        productService.save(product);
        return "redirect:/product/list";
    }

    // 跳转编辑页面
    @GetMapping("/edit/{id}")
    public String editPage(@PathVariable Integer id, Model model) {
        model.addAttribute("product", productService.findById(id));
        return "product/edit";
    }

    // 更新
    @PostMapping("/edit")
    public String edit(Product product) {
        productService.update(product);
        return "redirect:/product/list";
    }

    // 删除
    @PostMapping("/delete/{id}")
    public String delete(@PathVariable Integer id) {
        productService.delete(id);
        return "redirect:/product/list";
    }
}